package wiki.kaizen.cloud.shiro.stateless.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import wiki.kaizen.cloud.shiro.stateless.util.ISecurityUtil;

import javax.servlet.http.HttpServletResponse;

/**
 * 全局状态id uid的相应处理类
 * @author  xeepoo
 * */
@Configuration
public class ResponseUIDHandler implements ResponseBodyAdvice<Object> {


    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    /**
     * 请求头没有uid 则响应头设置uid
     * */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        this.setUid(
            request.getHeaders().getFirst("uid"),
            ((ServletServerHttpResponse)response).getServletResponse()
        );
        return body;
    }

    private void setUid(String requestHeaderUid,HttpServletResponse response){
        if (
            StringUtils.isEmpty(requestHeaderUid)
                &&
                StringUtils.isEmpty(response.getHeader("uid"))
        ){
            requestHeaderUid = ISecurityUtil.generateUID();
            response.addHeader("uid",requestHeaderUid);
        }
    }
}
